﻿#!/bin/bash
#author          :Ricardo de Souza Maia
#license         :GPLv3
#version         :$Id  
#encoding        :UTF-8
#Target          :GNU/Linux CentOS

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#                          CONFIGURAÇÃO DE VARIÁVEIS                          #
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#

#Diretorio Web Raiz
APACHE_WWW="/var/www/html"

#Pasta raiz da configuracoes do Apache
APACHE_ROOT="/etc/httpd"

#Configuracoes Adicionais do Apache
APACHE_CONF="$APACHE_ROOT/conf.d"

#Pasta de modulos do Apache
APACHE_MODS="$APACHE_ROOT/modules"

#Para para os virtual hosts
APACHE_VHOSTS="$APACHE_ROOT/virtual_hosts"

#--------------------- Não editar abaixo desta linha -------------------------

###############################################################################
# Tarefas iniciais do script
###############################################################################

#Inclui o arquivo de funcoes globais
CURRENT_DIR=$(cd $(dirname "$0"); pwd)
source "${CURRENT_DIR}/global_functions.sh"

clear
text_green
show_banner
text_normal

###############################################################################
# Testa se as pastas definidas existem
###############################################################################

if [ ! -d $APACHE_WWW ]; then
  echo "Erro: O diretório $APACHE_WWW não existe."
  exit 1
fi

if [ ! -d $APACHE_ROOT ]; then
  echo "Erro: O diretório $APACHE_ROOT não existe."
  exit 1
fi

if [ ! -d $APACHE_CONF ]; then
  echo "Erro: O diretório $APACHE_CONF não existe."
  exit 1
fi

if [ ! -d $APACHE_MODS ]; then
  echo "Erro: O diretório $APACHE_MODS não existe."
  exit 1
fi

if [ ! -d $APACHE_VHOSTS ]; then
  echo "Erro: O diretório $APACHE_VHOSTS não existe."
  exit 1
fi

###############################################################################
# Criação de novo usuário. Será utilizado pelo serviço FTP e quotas.
###############################################################################
while true
  read -p "Informe o nome de usuário: " USERNAME
  user_exists $USERNAME

 do
   if [ $? -eq 0 ]; then
    echo "Erro: O usuario '$USERNAME' já existe. Tente outro nome."
   else	 
     break
   fi;
 done
 
###############################################################################
# Define a quota de disco para o usuário criado
############################################################################### 
echo "ESPACO DISPONIVEL EM DISCO"
df -h --total

read -p "Informe a quota de disco para o usuario (em MB): " SOFTQUOTA
SOFTQUOTAKB=`expr $SOFTQUOTA \\* 1024`
HARDQUOTA=`expr $SOFTQUOTA + 50`
HARDQUOTAKB=`expr $HARDQUOTA \\* 1024`

echo "Você definiu uma quota de $SOFTQUOTA MB ($SOFTQUOTAKB KB) para o usuário $USERNAME"
echo "O usuário não terá permissão de escrita ao alcançar $HARDQUOTA MB ($HARDQUOTAKB KB) em disco."

###############################################################################
# Endereço do novo WebSite.
###############################################################################
read -p "Informe o nome do website (www.example.com): " WEBSITE_NAME


###############################################################################
# Porta TCP/IP para a nova instância do Apache
###############################################################################
while true
 read -p "Informe a porta do Apache (acima de 20000): " APACHE_PORT
 test_port $APACHE_PORT
 
 do
   if [ $? -eq 0 ]; then
    echo "Erro: A porta '$APACHE_PORT' está em uso. Tente outra porta."
   else
     break
   fi;
 done
 
###############################################################################
# Executando as operações configuradas
###############################################################################

#Adicionando usuario
useradd -m -d /var/www/html/$USERNAME -s /sbin/nologin $USERNAME

#Define a quota em disco para o usuario
setquota -u $USERNAME $SOFTQUOTAKB $HARDQUOTAKB 0 0 -a /var/www/html

#Cria o Virtual Host de Redirecionamento na instancia padrão do Apache
echo "
<VirtualHost *:80>
        ServerName $WEBSITE_NAME
        ProxyPass / http://localhost:$APACHE_PORT/
        ProxyPassReverse / http://localhost:$APACHE_PORT/
</VirtualHost>" > $APACHE_VHOSTS/$WEBSITE_NAME


#Adiciona uma nova instancia do apache
source "${CURRENT_DIR}/add_apache_instance.sh"
add_apache_instance $USERNAME

#Configura o virtual host da nova instância do Apache
echo "
User $USERNAME
Group $USERNAME

<VirtualHost *:$APACHE_PORT>
        ServerName $WEBSITE_NAME
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www/html/$USERNAME

        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>

        <Directory /var/www/html/$USERNAME>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog /var/log/httpd/error-$USERNAME.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/httpd/access-$USERNAME.log combined
</VirtualHost>" > $APACHE_ROOT-$USERNAME/virtual_hosts/default

#Reinicia a instância padrão e inicia a nova.
/etc/init.d/httpd restart
/etc/init.d/httpd-$USERNAME start


# httpd -f /etc/httpd-seplan/conf/httpd.conf -d /etc/httpd-seplan/

